package com.zzy.mccjt.core.interceptor;

import com.zzy.mccjt.exception.UnauthorizedException;
import com.zzy.mccjt.model.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zzy.mccjt.constant.RequestConstant.CURRENT_USER;
import static com.zzy.mccjt.constant.RequestConstant.C_USER_FLAG;

/**
 * @program: mccjt-cloud
 * @description:
 * @author: zhouyang.zheng
 * @create: 2022-08-02 17:41
 **/
@Slf4j
public class CRequestInterceptor extends AbstractRequestInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        if (isNoAuth(request, (HandlerMethod) handler)) {
            handleTenantInfo(request, (HandlerMethod) handler);
            return true;
        }

        String userId = request.getHeader(CURRENT_USER);
        if (StringUtils.isEmpty(userId)) {
            throw new UnauthorizedException(HttpStatus.UNAUTHORIZED.value(), "UNAUTHORIZED");
        } else {
            CurrentUser.set(C_USER_FLAG, Long.parseLong(userId));
        }

        handleTenantInfo(request, (HandlerMethod) handler);

        return true;
    }
}

